var wineApp = wineApp || {};
wineApp.ajax = (function() {
    function doAjax(url, method, params) {
        var fullUrl = wineApp.tool.getBaseApiURL() + url;
        console.log(fullUrl);
        var request = _.omit(params, ['async']);
        var async = params['async'];
        if (_.isNull(async) || _.isUndefined(async)) {
            async = true;
        }
        var deferred = $.Deferred();
        request['appid'] = wineApp.ajax.getAppid();
        request['time'] = _.now();
        var sign = signParam(request)
        request['sign'] = sign;
        console.log(JSON.stringify(request));
        $.ajax({
                url: fullUrl,
                type: method,
                dataType: 'json',
                async: async,
                cache: false,
                contentType: 'application/x-www-form-urlencoded',
                data: JSON.stringify(request),
                dataFilter: function(data) {
                    var tmp = data.replace(/\r\n/g, '\\r\\n');
                    return tmp;
                }
            }).done(function(data) {
                console.log('response from server:%O', data)
                if (data.code === 0) {
                    deferred.resolve(data);
                } else {
                    console.log('api fail:%O', data)
                    deferred.reject(data);
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                console.log('jqXHR:%O', jqXHR)
                deferred.reject(jqXHR);
            });
        return deferred.promise();
    }

    var spin = new Spinner({ lines: 10, length: 4, width: 2, radius: 5 });
    var initLoading = function() {
        $(document).ajaxStart(function() {
            wineApp.ajax.showLoading();
        });

        $(document).ajaxStop(function() {
            wineApp.ajax.hideLoading();
        });

    }

    var showLoading = function() {
        var maskDiv = $('<div class="loadmask"></div>');
        //maskDiv.css("top",$(document).scrollTop());
        $(document.body).append(maskDiv);
        spin.spin(document.body);
    }

    var hideLoading = function() {
        $(document.body).find(".loadmask").remove();
        spin.stop();
    }

    /**
     * 对参数进行排序，返回key1=aaa&key2=bbb的字符串
     */
    var sortParam = function(data) {
        var keys = _.keys(data);
        var sortedKeys = _.sortBy(keys, function(key) {
            return key;
        });
        var param = _.chain(sortedKeys).map(function(key) {
            var obj = data[key];
            if (_.isObject(obj)) {
                obj = JSON.stringify(obj)
            }
            return key + "=" + obj;
        }).join('&').value();
        console.log('befor sign:.%O', param);
        return param;
    }

    var signParam = function(paramObj) {
        var appid = getAppid();
        var appcert = getCert();
        console.log('token:' + appcert);
        var sign = CryptoJS.MD5(sortParam(paramObj)).toString();
        return CryptoJS.MD5(appid + "&" + sign + "&" + appcert).toString();
    }

    var doGet = function(url) {
        return doAjax(url, 'get', {});
    };

    var doPost = function(url, params) {
        return doAjax(url, 'post', params);
    };

    var doPut = function(url, params) {
        return doAjax(url, 'put', params);
    };

    var doDel = function(url, params) {
        return doAjax(url, 'delete', params);
    };

    var getAppid = function() {
        var key = wineApp.tool.getKey('APP_ID');
        var deviceId = _.now();
        if (window.device) {
            deviceId = device.uuid;
        } else {
            console.log('getUUid error');
        }
        var appId = wineApp.localStorage.get(key)
        if (_.isNull(appId) || _.isEmpty(appId)) {
            appId = CryptoJS.MD5(deviceId + "").toString();
            wineApp.localStorage.set(key, appId);
        }
        return appId;
    }
    var getCert = function() {
        var key = wineApp.tool.getKey('APP_CERT');
        var cert = wineApp.localStorage.get(key);
        return cert;
    }

    return {
        get: doGet,
        post: doPost,
        put: doPut,
        del: doDel,
        initLoading: initLoading,
        showLoading: showLoading,
        hideLoading: hideLoading,
        getAppid: getAppid,
        getCert: getCert,
        signParam: signParam
    }

})();

jQuery(document).ready(function($) {
    wineApp.ajax.initLoading();
});